<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  

  
  <title>ES6 Promise用法总结 | Hexo</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <meta name="description" content="Promise的出现是为了解决函数回调地狱的问题，但并没有消除回调，只是让回调变得可控">
<meta property="og:type" content="article">
<meta property="og:title" content="ES6 Promise用法总结">
<meta property="og:url" content="http://yoursite.com/2020/06/13/ES6%20Promise%E7%94%A8%E6%B3%95%E6%80%BB%E7%BB%93/index.html">
<meta property="og:site_name" content="Hexo">
<meta property="og:description" content="Promise的出现是为了解决函数回调地狱的问题，但并没有消除回调，只是让回调变得可控">
<meta property="og:locale" content="en_US">
<meta property="og:image" content="http://yoursite.com/2020/06/13/ES6%20Promise%E7%94%A8%E6%B3%95%E6%80%BB%E7%BB%93/img/%E5%9B%BE%E4%BE%8B.png">
<meta property="article:published_time" content="2020-06-13T10:06:22.000Z">
<meta property="article:modified_time" content="2020-07-30T13:04:01.598Z">
<meta property="article:author" content="John Doe">
<meta property="article:tag" content="js">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://yoursite.com/2020/06/13/ES6%20Promise%E7%94%A8%E6%B3%95%E6%80%BB%E7%BB%93/img/%E5%9B%BE%E4%BE%8B.png">
  
    <link rel="alternate" href="/atom.xml" title="Hexo" type="application/atom+xml">
  
  
    <link rel="icon" href="/favicon.png">
  
  
    <link href="//fonts.googleapis.com/css?family=Source+Code+Pro" rel="stylesheet" type="text/css">
  
  
<link rel="stylesheet" href="/css/style.css">

<meta name="generator" content="Hexo 5.0.0"></head>

<body>
  <div id="container">
    <div id="wrap">
      <header id="header">
  <div id="banner"></div>
  <div id="header-outer" class="outer">
    <div id="header-title" class="inner">
      <h1 id="logo-wrap">
        <a href="/" id="logo">Hexo</a>
      </h1>
      
    </div>
    <div id="header-inner" class="inner">
      <nav id="main-nav">
        <a id="main-nav-toggle" class="nav-icon"></a>
        
          <a class="main-nav-link" href="/">Home</a>
        
          <a class="main-nav-link" href="/archives">Archives</a>
        
      </nav>
      <nav id="sub-nav">
        
          <a id="nav-rss-link" class="nav-icon" href="/atom.xml" title="RSS Feed"></a>
        
        <a id="nav-search-btn" class="nav-icon" title="Search"></a>
      </nav>
      <div id="search-form-wrap">
        <form action="//google.com/search" method="get" accept-charset="UTF-8" class="search-form"><input type="search" name="q" class="search-form-input" placeholder="Search"><button type="submit" class="search-form-submit">&#xF002;</button><input type="hidden" name="sitesearch" value="http://yoursite.com"></form>
      </div>
    </div>
  </div>
</header>
      <div class="outer">
        <section id="main"><article id="post-ES6 Promise用法总结" class="article article-type-post" itemscope itemprop="blogPost">
  <div class="article-meta">
    <a href="/2020/06/13/ES6%20Promise%E7%94%A8%E6%B3%95%E6%80%BB%E7%BB%93/" class="article-date">
  <time datetime="2020-06-13T10:06:22.000Z" itemprop="datePublished">2020-06-13</time>
</a>
    
  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 class="article-title" itemprop="name">
      ES6 Promise用法总结
    </h1>
  

      </header>
    
    <div class="article-entry" itemprop="articleBody">
      
        <p><strong>Promise的出现是为了解决函数回调地狱的问题，但并没有消除回调，只是让回调变得可控</strong><br> <img src="img/%E5%9B%BE%E4%BE%8B.png" alt="promise"><br> <a id="more"></a><br> 上图是关于promise执行的流程图，promise有3种状态:</p>
<ul>
<li>pending（未决阶段）</li>
</ul>
<ul>
<li>resolved （已决阶段）</li>
<li>rejected  （已决阶段）<br>其中在未决(pending)阶段需要做一些例如：发送ajax请求等都是在这个阶段进行的， <code>注意：在pending阶段的代码是同步执行的，当promise被创建时，其里面的回调函数立即被执行</code><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"> <span class="keyword">const</span> pro = <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">            <span class="comment">// 未决阶段的处理</span></span><br><span class="line">            <span class="comment">// 通过调用resolve函数将Promise推向已决阶段的resolved状态</span></span><br><span class="line">            <span class="comment">// 通过调用reject函数将Promise推向已决阶段的rejected状态</span></span><br><span class="line">            <span class="comment">// resolve和reject均可以传递最多一个参数，表示推向状态的数据</span></span><br><span class="line">            <span class="built_in">console</span>.log(<span class="number">1</span>);</span><br><span class="line">            <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">                <span class="built_in">console</span>.log(<span class="number">2</span>)</span><br><span class="line">                resolve(<span class="number">123</span>) <span class="comment">//将状态推向已决 resolved状态</span></span><br><span class="line">            &#125;, <span class="number">0</span>)</span><br><span class="line">            <span class="built_in">console</span>.log(<span class="number">3</span>)</span><br><span class="line">        &#125;)</span><br><span class="line">        <span class="comment">// 依次输出 1 3 2</span></span><br><span class="line">&#125;)</span><br><span class="line"></span><br></pre></td></tr></table></figure>
resolved就是将”未决状态”变为”成功”即从”pending”到”resolved”。rejected就是将”未决状态”变为”失败”即从”pending”到”rejected”，它们都可以将函数的处理结构作为参数返回出去。  <h5 id="then"><a href="#then" class="headerlink" title=".then()"></a>.then()</h5>哈哈，这是我总结的第一个方法。Promise.then()是当promise的状态从未决阶段到已决阶段后，要执行的后续操作，promise状态一经改变，不会再变。<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">pro.then(<span class="function"><span class="params">data</span>=&gt;</span>&#123;</span><br><span class="line">   <span class="comment">//这是一个thenable函数，当如果当前是resolve状态时，就会触发这个函数</span></span><br><span class="line">   <span class="comment">//如果当前是未决阶段则会加入作业队列， 等待resolved状态后执行</span></span><br><span class="line">   <span class="comment">//data为pending状态时传递过来的状态数据</span></span><br><span class="line">&#125;.error=&gt;&#123;</span><br><span class="line"> <span class="comment">//这是一个catchable函数，当如果当前是reject状态时，就会触发这个函数</span></span><br><span class="line"> <span class="comment">//如果当前是未决阶段则会加入作业队列， 等待rejected状态后执行</span></span><br><span class="line">   <span class="comment">//data为pending状态时传递过来的状态数据</span></span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
==注意：.then()方法返回的仍然是一个全新的promise对象，其返回值与状态是由当前Promise决定的==</li>
</ul>
<ol>
<li><p>如何当前的promise是未决的，得到的新的promise是挂起状态</p>
</li>
<li><p>如何当前的promise是已决的，会运行响应的后续处理函数，并将后续处理函数的结果（返回值）作为resolve的状态数据，应用到新的Promise中;如何后续处理函数出现错误则会把rejected状态数据应用到新的promise中</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> pro = <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">           resolve(<span class="number">111</span>)</span><br><span class="line">       &#125;)</span><br><span class="line"></span><br><span class="line">       <span class="keyword">const</span> pro2 = pro.then(<span class="function"><span class="params">data</span> =&gt;</span> &#123;</span><br><span class="line"></span><br><span class="line">           <span class="keyword">if</span> (data &gt; <span class="number">20</span>) &#123;</span><br><span class="line">               <span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">Error</span>(<span class="string">&#x27;1111&#x27;</span>)</span><br><span class="line"></span><br><span class="line">           &#125; <span class="keyword">else</span> <span class="keyword">if</span> (data &gt; <span class="number">10</span>) &#123;</span><br><span class="line">               <span class="keyword">throw</span> <span class="keyword">new</span> error(<span class="string">&#x27;1111&#x27;</span>)</span><br><span class="line">           &#125;</span><br><span class="line">       &#125;, <span class="function"><span class="params">err</span> =&gt;</span> &#123;</span><br><span class="line"></span><br><span class="line">       &#125;)</span><br><span class="line">       <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">           <span class="built_in">console</span>.log(pro2) <span class="comment">// pro2为rejected状态，因为后续处理函数抛出了错误</span></span><br><span class="line">       &#125;, <span class="number">1000</span>)</span><br><span class="line">       <span class="built_in">console</span>.log(pro2)   <span class="comment">// pro2为pending状态,因为此时的pro是pending的</span></span><br></pre></td></tr></table></figure>
<h4 id="all-iterable"><a href="#all-iterable" class="headerlink" title=".all(iterable)"></a>.all(iterable)</h4><p>这个方法返回的是一个新的promise对象，该promise对象在iterable参数对象里都成果才会触发成功。一旦任何一个iterable里的promise对象失败则会立即触发该promise对象的失败。这个新的promise函数触发成功之后会将，一个包含iterable里面的所有promise对象的数组作为成功回调的返回值，顺序跟iterable保持一致；如果这个新的promise对象触发了失败状态，它会把iterable里第一个触发promise对象的错误信息作为它失败的错误信息。Promise.all 方法常被用于处理多个promise对象的集合</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">getRandom</span>(<span class="params">min, max</span>) </span>&#123;</span><br><span class="line">         <span class="keyword">return</span> <span class="built_in">Math</span>.random() * (max - min) + min</span><br><span class="line">     &#125;</span><br><span class="line">     <span class="keyword">const</span> proms = []</span><br><span class="line">     <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; <span class="number">10</span>; i++) &#123;</span><br><span class="line">         proms.push(<span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">             <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">                 consoloe.log(i, <span class="string">&quot;完成&quot;</span>)</span><br><span class="line">                 resolve(i)</span><br><span class="line">             &#125;,getRandom(<span class="number">1000</span>, <span class="number">3000</span>))</span><br><span class="line">         &#125;))</span><br><span class="line">     &#125;</span><br><span class="line">     <span class="comment">// 等到所有的promise变成resolved状态后输出全部完成</span></span><br><span class="line">     <span class="keyword">const</span> pro = <span class="built_in">Promise</span>.all(proms)</span><br><span class="line">     pro.then(<span class="function"><span class="params">datas</span> =&gt;</span> &#123;</span><br><span class="line">         <span class="built_in">console</span>.log(<span class="string">&quot;全部完成&quot;</span>,datas) <span class="comment">//[1,2,3,4,5,6,7,8,9,10] 返回每一个promise成功之后的状态数据</span></span><br></pre></td></tr></table></figure>
<h4 id="race-iterable"><a href="#race-iterable" class="headerlink" title=".race(iterable)"></a>.race(iterable)</h4><p>当iterable参数里的任何一个子promise被成功或失败后，父promise会立即使用子promise的成功值或者失败值，作为父promise的状态数据，返回该promise</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">getRandom</span>(<span class="params">min, max</span>) </span>&#123;</span><br><span class="line">         <span class="keyword">return</span> <span class="built_in">Math</span>.random() * (max - min) + min</span><br><span class="line">     &#125;</span><br><span class="line">     <span class="keyword">const</span> proms = []</span><br><span class="line">     <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; <span class="number">10</span>; i++) &#123;</span><br><span class="line">         proms.push(<span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">             <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">                 <span class="keyword">if</span> (<span class="built_in">Math</span>.random() &gt; <span class="number">0.5</span>) &#123;</span><br><span class="line">                     resolve(i + <span class="string">&#x27;率先成功&#x27;</span>)</span><br><span class="line">                 &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                     reject(i + <span class="string">&#x27;率先失败&#x27;</span>)</span><br><span class="line">                 &#125;</span><br><span class="line">             &#125;, getRandom(<span class="number">1000</span>, <span class="number">2000</span>))</span><br><span class="line">         &#125;))</span><br><span class="line">     &#125;</span><br><span class="line">     <span class="comment">// 只要proms 中有一个promise先推向成功或者失败就将状态数据值传递给datas</span></span><br><span class="line">     <span class="keyword">const</span> pro = <span class="built_in">Promise</span>.race(proms)</span><br><span class="line">     pro.then(<span class="function"><span class="params">datas</span> =&gt;</span> &#123;</span><br><span class="line">         <span class="built_in">console</span>.log(datas) <span class="comment">// 输出一个状态数据</span></span><br><span class="line">     &#125;)</span><br></pre></td></tr></table></figure>
<h4 id="其他的api"><a href="#其他的api" class="headerlink" title="其他的api"></a>其他的api</h4><p>finally : [es2018]注册一个后续处理函数（无参），当promise已决时运行该函数<br>resolved : 该方法返回一个resolved状态的promise，传递的数据作为状态数据</p>
<pre><code>    特殊情况：如果传递的数据是promise，则直接返回Promsie对象 </code></pre>
<p>rejected : 该方法返回一个rejected 状态的promise，传递的数据作为状态数据   </p>
</li>
</ol>

      
    </div>
    <footer class="article-footer">
      <a data-url="http://yoursite.com/2020/06/13/ES6%20Promise%E7%94%A8%E6%B3%95%E6%80%BB%E7%BB%93/" data-id="ckd8udtbc00029gt4fgcs0tff" class="article-share-link">Share</a>
      
      
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/js/" rel="tag">js</a></li></ul>

    </footer>
  </div>
  
    
<nav id="article-nav">
  
    <a href="/2020/06/15/%E5%89%96%E6%9E%90Vue%E7%9A%84%E5%93%8D%E5%BA%94%E5%BC%8F/" id="article-nav-newer" class="article-nav-link-wrap">
      <strong class="article-nav-caption">Newer</strong>
      <div class="article-nav-title">
        
          剖析Vue的响应式
        
      </div>
    </a>
  
  
    <a href="/2020/06/10/JS%E4%B8%AD%E7%9A%84%E9%97%AD%E5%8C%85%E9%97%AE%E9%A2%98%EF%BC%8C%E9%97%AD%E5%8C%85%E7%9A%84%E9%82%A3%E6%98%AF%E4%BA%9B%E4%BA%8B/" id="article-nav-older" class="article-nav-link-wrap">
      <strong class="article-nav-caption">Older</strong>
      <div class="article-nav-title">JS中的闭包问题，闭包的那是些事</div>
    </a>
  
</nav>

  
</article>

</section>
        
          <aside id="sidebar">
  
    

  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Tags</h3>
    <div class="widget">
      <ul class="tag-list" itemprop="keywords"><li class="tag-list-item"><a class="tag-list-link" href="/tags/Vue/" rel="tag">Vue</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/Vue%E5%85%A8%E5%AE%B6%E6%A1%B6/" rel="tag">Vue全家桶</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/js/" rel="tag">js</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/node/" rel="tag">node</a></li></ul>
    </div>
  </div>


  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Tag Cloud</h3>
    <div class="widget tagcloud">
      <a href="/tags/Vue/" style="font-size: 20px;">Vue</a> <a href="/tags/Vue%E5%85%A8%E5%AE%B6%E6%A1%B6/" style="font-size: 10px;">Vue全家桶</a> <a href="/tags/js/" style="font-size: 15px;">js</a> <a href="/tags/node/" style="font-size: 10px;">node</a>
    </div>
  </div>

  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Archives</h3>
    <div class="widget">
      <ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/archives/2020/07/">July 2020</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2020/06/">June 2020</a></li></ul>
    </div>
  </div>


  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Recent Posts</h3>
    <div class="widget">
      <ul>
        
          <li>
            <a href="/2020/07/30/hello-world/">我的第一章博客</a>
          </li>
        
          <li>
            <a href="/2020/07/25/%E5%8E%9F%E7%94%9FHttp%E5%AE%9E%E7%8E%B0cookie%E8%AE%BE%E7%BD%AE/">原生Http实现cookie设置</a>
          </li>
        
          <li>
            <a href="/2020/07/23/%E5%B0%81%E8%A3%85Vue%E7%BB%84%E4%BB%B6%E5%B0%86%E4%BB%BB%E6%84%8F%E5%90%8E%E7%BC%80%E6%96%87%E4%BB%B6%E7%9B%AE%E5%BD%95%E7%BB%9F%E4%B8%80%E5%85%A8%E9%83%A8%E5%BC%95%E5%85%A5%E5%88%B0%E5%BD%93%E5%89%8D%E6%96%87%E4%BB%B6/">封装Vue组件将任意后缀文件目录统一全部引入到当前文件</a>
          </li>
        
          <li>
            <a href="/2020/07/15/js%E4%B8%AD%E7%9A%84%E9%98%B2%E6%8A%96%E4%B8%8E%E8%8A%82%E6%B5%81/">js中的防抖与节流</a>
          </li>
        
          <li>
            <a href="/2020/07/07/%E6%89%8B%E5%8A%A8%E5%AE%9E%E7%8E%B0call%EF%BC%8Capply,bind/">手动实现call，apply,bind</a>
          </li>
        
      </ul>
    </div>
  </div>

  
</aside>
        
      </div>
      <footer id="footer">
  
  <div class="outer">
    <div id="footer-info" class="inner">
      &copy; 2020 John Doe<br>
      Powered by <a href="http://hexo.io/" target="_blank">Hexo</a>
    </div>
  </div>
</footer>
    </div>
    <nav id="mobile-nav">
  
    <a href="/" class="mobile-nav-link">Home</a>
  
    <a href="/archives" class="mobile-nav-link">Archives</a>
  
</nav>
    

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>


  
<link rel="stylesheet" href="/fancybox/jquery.fancybox.css">

  
<script src="/fancybox/jquery.fancybox.pack.js"></script>




<script src="/js/script.js"></script>




  </div>
</body>
</html>